package com.zl.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zl.common.Constant;
import com.zl.common.thread.TokenThread;
import com.zl.dao.UserDao;
import com.zl.entity.NewsEntity;
import com.zl.entity.QueryEntity;
import com.zl.util.SearchUtils;
import com.zl.weixin.entity.AccessToken;
import com.zl.weixin.entity.UserClient;
import com.zl.weixin.entity.message.resp.Article;
import com.zl.weixin.entity.message.resp.NewsMessage;
import com.zl.weixin.entity.message.resp.TextMessage;
import com.zl.weixin.util.MessageUtil;
import com.zl.weixin.util.WeixinUtil;

@Service
public class WeixinService {
	@Autowired
	private UserDao userDao;
	public String processRequest(HttpServletRequest request) {
		Logger log = Logger.getLogger(WeixinService.class);
		String respMessage = null;
		AccessToken at = TokenThread.accessToken;
		try {
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			String respContent = "";
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(Constant.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			// 接受的文本消息
			if (msgType.equals(Constant.REQ_MESSAGE_TYPE_TEXT)) {
				// 接收用户发送的文本消息内容
				String content = requestMap.get("Content");
				String userId = requestMap.get("FromUserName");
				String createTime = requestMap.get("CreateTime");
				// Date createDate = sdf.parse(createTime);
				String msgId = requestMap.get("MsgId");
				NewsMessage newsMessage = new NewsMessage();
				newsMessage.setToUserName(fromUserName);
				newsMessage.setFromUserName(toUserName);
				newsMessage.setCreateTime(new Date().getTime());
				newsMessage.setMsgType(Constant.RESP_MESSAGE_TYPE_NEWS);
				newsMessage.setFuncFlag(0);
				if (StringUtils.isNotBlank(content)) {
				int i = 0;
				String keyword = content;
				QueryEntity queryEntity = new QueryEntity();
				queryEntity.setPage(0);
				queryEntity.setKeywords(keyword);
				List<NewsEntity> list = SearchUtils.search(queryEntity);
				List<Article> articleList = new ArrayList<Article>();
				String url = "http://121.43.226.252/zzd-web/";
				for (NewsEntity news : list) {
					if(i<7){
						
					
					Article article = new Article();
					article.setTitle(news.getTitle()+"["+news.getType()+"]");
					article.setDescription(news.getTitle());
					if(news.getCategory().contains("gg")){
						if(i==0){
							article.setPicUrl(url+"images/zbgg.jpg");
						}else{
							article.setPicUrl(url+"images/zbgg_y.jpg");
						}
					}else{
						if(i==0){
							article.setPicUrl(url+"images/zbjg.jpg");
						}else{
							article.setPicUrl(url+"images/zbjg_y.jpg");
						}
					}
					
					
					article.setUrl(url+"detail/index?id="+news.getId()+"&type="+news.getTableName());
					articleList.add(article);
					i++;
					}
				}
				if (articleList.size() > 0) {
					Article article1 = new Article();
					article1.setTitle("更多");
					article1.setUrl(url+"search/index");
					articleList.add(article1);
					// 设置图文消息个数
					newsMessage.setArticleCount(articleList.size());
					// 设置图文消息包含的图文集合
					newsMessage.setArticles(articleList);
					// 将图文消息对象转换成xml字符串
					respMessage = MessageUtil.newsMessageToXml(newsMessage);
				} else {
					respContent = "没有搜索到您输入的内容";
					textMessage.setContent(respContent);
					respMessage = MessageUtil.textMessageToXml(textMessage);
				}
				}

			} else if (msgType.equals(Constant.REQ_MESSAGE_TYPE_IMAGE)) {
				String userId = requestMap.get("FromUserName");
				String createTime = requestMap.get("CreateTime");
				// Date createDate = sdf.parse(createTime);
				String msgId = requestMap.get("MsgId");
				String imgId = requestMap.get("MediaId");
				String picUrl = requestMap.get("PicUrl");
				UserClient user = WeixinUtil.getUser(at.getToken(), userId);
				String filename = WeixinUtil.getPic(at.getToken(), imgId);
				String allfile = filename;
				// 图片
			}
			// 语音消息
			else if (msgType.equals(Constant.REQ_MESSAGE_TYPE_VOICE)) {

			}
			// 事件消息
			else if (msgType.equals(Constant.REQ_MESSAGE_TYPE_EVENT)) {
				String eventType = requestMap.get("Event");
				if (eventType.equals(Constant.EVENT_TYPE_SUBSCRIBE)) {
					String id = fromUserName;
					UserClient userClient = userDao.getUserById(id);
					if(userClient==null){
						UserClient user= WeixinUtil.getUser(at.getToken(), id);
						userDao.insertUser(user);
					}
					// 关注事件
					respContent = "欢迎您关注招标我知道。你订阅，我推送，全国招投标信息一网打尽！<a href='http://mp.weixin.qq.com/s?__biz=MzAwNTU0MDM3Mg==&mid=207459140&idx=1&sn=3861560acfb4405177496d5bd8697b7d#rd'>点击查看使用指南</a>。";
					textMessage.setContent(respContent);
					respMessage = MessageUtil.textMessageToXml(textMessage);

				} else if (eventType.equals(Constant.EVENT_TYPE_UNSUBSCRIBE)) {
					// 取消关注,用户接受不到我们发送的消息了，可以在这里记录用户取消关注的日志信息

				}else if (eventType.equals(Constant.EVENT_TYPE_SCAN)) {
					// 扫描二维码参数事件
					String eventKey = requestMap.get("EventKey");
					respContent = "扫描了带参数的二维码参数："+eventKey;
					textMessage.setContent(respContent);
					respMessage = MessageUtil.textMessageToXml(textMessage);

				} else if (eventType.equals(Constant.EVENT_TYPE_CLICK)) {

					// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					String eventKey = requestMap.get("EventKey");
					NewsMessage newsMessage = new NewsMessage();
					newsMessage.setToUserName(fromUserName);
					newsMessage.setFromUserName(toUserName);
					newsMessage.setCreateTime(new Date().getTime());
					newsMessage.setMsgType(Constant.RESP_MESSAGE_TYPE_NEWS);
					newsMessage.setFuncFlag(0);
					// 自定义菜单点击事件
					if (eventKey.equals("33")) {
						List<Article> articleList = new ArrayList<Article>();
						Article article = new Article();
						article.setTitle("招标我知道使用帮助");
						article.setPicUrl("http://mmbiz.qpic.cn/mmbiz/aetlPBCNx2Bueec6uPSNHFGULXurNvjwuVt1UFgy3rHzK9C9bOBDj0kATic3HsuicibB2y9d9cd57mlLE7XYZT4Zg/640?wx_fmt=jpeg&amp;tp=webp&amp;wxfrom=5");
						article.setUrl("http://mp.weixin.qq.com/s?__biz=MzAwNTU0MDM3Mg==&mid=207459140&idx=1&sn=3861560acfb4405177496d5bd8697b7d#rd");
						article.setDescription("招标我知道使用帮助手册");
						articleList.add(article);
						newsMessage.setArticleCount(articleList.size());
						// 设置图文消息包含的图文集合
						newsMessage.setArticles(articleList);
						// 将图文消息对象转换成xml字符串
						respMessage = MessageUtil.newsMessageToXml(newsMessage);
					} // 自定义菜单点击事件
					else if (eventKey.equals("34")) {
						List<Article> articleList = new ArrayList<Article>();
						Article article = new Article();
						article.setTitle("招标我知道抽奖活动");
						article.setPicUrl("http://mmbiz.qpic.cn/mmbiz/aetlPBCNx2BaJTVXciae3CIzliaiaPCMgr4dtTSNPJzZIbemdkyyiaOvPpGdaVHzho0aicPItKzickwIgHxLHLvW2FMw/640?wx_fmt=jpeg&tp=webp&wxfrom=5");
						article.setUrl("http://mp.weixin.qq.com/s?__biz=MzAwNTU0MDM3Mg==&mid=207699617&idx=1&sn=f2c8a2f4381f050c8b1ebb37875211ec#rd");
						article.setDescription("招标我知道抽奖活动说明");
						articleList.add(article);
						newsMessage.setArticleCount(articleList.size());
						// 设置图文消息包含的图文集合
						newsMessage.setArticles(articleList);
						// 将图文消息对象转换成xml字符串
						respMessage = MessageUtil.newsMessageToXml(newsMessage);
					}
					else if (eventKey.equals("12")) {
						respContent = "公交查询菜单项被点击！";
					} else if (eventKey.equals("13")) {
						respContent = "宁波市公安局 地址：宁波市江东区中兴路658号！";
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
					} else if (eventKey.equals("31")) {
						
						// 设置图文消息个数
						
					} else if (eventKey.equals("32")) {
						respContent = "正在开发中";
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
					}
				}
				// textMessage.setContent(respContent);
				// respMessage = MessageUtil.textMessageToXml(textMessage);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.print("MYSQL ERROR:" + e.getMessage());
		}
		return respMessage;
	}
}
